﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using YiNing.Tools.Args;
using YiNing.UI.Controls;
using YiNing.UI.Forms;
using YiNing.UI.Tools;
using static YiNing.UI.Config.Enums;

namespace YiNing.Tools
{
    public partial class MappingFilter : Form
    {
        TestProgramConfig  programConfig;
        ProductMappingArgs productMappingArgs = ProductMappingArgs.Default();
        List<Die> diesList = new List<Die>();

        public MappingFilter()
        {
            diesList.Clear();
            InitializeComponent();
            ControlHelper.SetDarkButtonClick(new Control[] { this }, DarkButton_Click);
            wafermapLeft.Colors = Die.DefaultColors;
            wafermapRight.Colors = Die.DefaultColors;
            wafermapLeft.Interactive = true;
            wafermapRight.Interactive = true;
            wafermapLeft.OnDieClick += Wafermap1_OnDieClick;
            wafermapRight.OnDieClick += Wafermap2_OnDieClick;
            darkComboBox1.SelectedIndex = 0;
            darkComboBox1.Text = "左";
            darkComboBox1.SelectedText = "左";
            propertyGrid1.SelectedObject = productMappingArgs;
            //var softwareMapping = WaferMappingHelper.MappingAnalysis(@"D:\QTWaferProgram\384-0801\384.txt", ' ', 3);
        }


        private void Wafermap2_OnDieClick(object sender, Die e)
        {
            dlbProductMappingSelect.Text = string.Format("当前选中: [x: {0} y:{1}]", e.XIndex, e.YIndex);
        }

        private void Wafermap1_OnDieClick(object sender, Die e)
        {
            dlbSoftwareMappingSelect.Text = string.Format("当前选中: [x: {0} y:{1}]", e.XIndex, e.YIndex);
        }

        private void DarkButton_Click(object sender, EventArgs e)
        {
            DarkButton btn = sender as DarkButton;
            string type = btn.Tag.ToString();
            switch (type)
            {
                case "顺时针旋转90°":
                    //var aaaa = WaferMappingHelper.MappingAnalysis(@"C:\Users\Administrator\Documents\WeChat Files\wfylozj\FileStorage\File\2022-02\H3817C1S3_M21B077_08.txt");
                    RotateProductMapping(90);
                    break;
                case "逆时针旋转90°":
                    //var aaaa2 = WaferMappingHelper.MappingAnalysis(@"C:\Users\Administrator\Documents\WeChat Files\wfylozj\FileStorage\File\2022-02\H3817C1S3_M21B077_08.txt");
                    RotateProductMapping(-90);
                    break;
                case "open Form1":
                    new Form1().Show();
                    break;
                case "加载程式图谱":
                    LoadMapping();
                    break;
                case "加载产品图谱":
                    LoadSoftwareMapping();
                    break;
                case "重置":
                    nonWafermapRight.Dataset = null;
                    wafermapRight.Dataset = null;
                    break;
                case "图谱对位":
                    MappingContraposition();
                    break;
                case "导出到该程式并退出":
                    ExportFilterMapping();
                    break;
                case "改变方向":

                    List<Quad> aaa = new List<Quad>();
                    aaa.Add(new Quad(1, 1, 2, 3));
                    aaa.Add(new Quad(5, 4, 2, 3));
                    JsonHelper.Serialize(aaa, "E:/aaaa.json");
                    //nonstandardWafermap1.Zoom = 1f;
                    //nonstandardWafermap1.Rotation += 90;
                    break;
                case "生成测试图谱":
                    #region 生成测试图谱
                    double dieWidth = 1000, dieHeight = 5000;
                    Point waferCenter = new Point(139524, 114250);

                    List<Die> dies = new List<Die>();
                    Die tempFuck = new Die() { XIndex = 0, YIndex = 0, ColorIndex = 1, XPluse = waferCenter.X, YPluse = waferCenter.Y, WaferCenterXPulse = waferCenter.X, WaferCenterYPulse = waferCenter.Y, WaferRadius = 99575.929852770831 };
                    tempFuck.DieQuad = new Quad
                        (tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).Y,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).Y);
                    dies.Add(tempFuck);

                    tempFuck = new Die() { XIndex = 0, YIndex = 0, ColorIndex = 1, XPluse = waferCenter.X, YPluse = Convert.ToInt32(waferCenter.Y + 99575.929852770831 / 2), WaferCenterXPulse = waferCenter.X, WaferCenterYPulse = waferCenter.Y, WaferRadius = 99575.929852770831 };
                    tempFuck.DieQuad = new Quad
                        (tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).Y,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).Y);
                    dies.Add(tempFuck);

                    dieWidth = 5000; dieHeight = 1000;
                    tempFuck = new Die() { XIndex = 0, YIndex = 0, ColorIndex = 1, XPluse = Convert.ToInt32(waferCenter.X + 99575.929852770831 / 2), YPluse =waferCenter.Y, WaferCenterXPulse = waferCenter.X, WaferCenterYPulse = waferCenter.Y, WaferRadius = 99575.929852770831 };
                    tempFuck.DieQuad = new Quad
                        (tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).Y,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).Y);
                    dies.Add(tempFuck);

                    dieWidth = 6000; dieHeight = 4000;
                    tempFuck = new Die() { XIndex = 0, YIndex = 0, ColorIndex = 1, XPluse = Convert.ToInt32(waferCenter.X - 99575.929852770831 / 2), YPluse = waferCenter.Y, WaferCenterXPulse = waferCenter.X, WaferCenterYPulse = waferCenter.Y, WaferRadius = 99575.929852770831 };
                    tempFuck.DieQuad = new Quad
                        (tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).Y,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).Y);
                    dies.Add(tempFuck);


                    tempFuck = new Die() { XIndex = 0, YIndex = 0, ColorIndex = 1, XPluse = waferCenter.X, YPluse = Convert.ToInt32(waferCenter.Y - 99575.929852770831 / 2), WaferCenterXPulse = waferCenter.X, WaferCenterYPulse = waferCenter.Y, WaferRadius = 99575.929852770831 };
                    tempFuck.DieQuad = new Quad
                        (tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectLeftBottomPoint(true, 1, 1, dieWidth, dieHeight).Y,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).X,
                        tempFuck.GetDieRectRightTopPoint(true, 1, 1, dieWidth, dieHeight).Y);
                    dies.Add(tempFuck);
                    //Die[,] data = JsonHelper.DeserializeByFile<Die[,]>(@"D:\QTWaferProgram\3812\mapping.zyn");
                    //Die tempDie = data[9, 4];
                    //tempDie.DieQuad = new Quad
                    //    (tempDie.GetDieRectLeftBottomPoint(1, 1, dieWidth, dieHeight).X,
                    //    tempDie.GetDieRectLeftBottomPoint(1, 1, dieWidth, dieHeight).Y,
                    //    tempDie.GetDieRectRightTopPoint(1, 1, dieWidth, dieHeight).X,
                    //    tempDie.GetDieRectRightTopPoint(1, 1, dieWidth, dieHeight).Y);
                    //dies.Add(tempDie);

                    //tempDie = data[15, 9];
                    //tempDie.DieQuad = new Quad
                    //    (tempDie.GetDieRectLeftBottomPoint(1, 1, dieWidth, dieHeight).X,
                    //    tempDie.GetDieRectLeftBottomPoint(1, 1, dieWidth, dieHeight).Y,
                    //    tempDie.GetDieRectRightTopPoint(1, 1, dieWidth, dieHeight).X,
                    //    tempDie.GetDieRectRightTopPoint(1, 1, dieWidth, dieHeight).Y);
                    //dies.Add(tempDie);

                    //tempDie = data[11, 10];
                    //tempDie.DieQuad = new Quad
                    //    (tempDie.GetDieRectLeftBottomPoint(1, 1, dieWidth, dieHeight).X,
                    //    tempDie.GetDieRectLeftBottomPoint(1, 1, dieWidth, dieHeight).Y,
                    //    tempDie.GetDieRectRightTopPoint(1, 1, dieWidth, dieHeight).X,
                    //    tempDie.GetDieRectRightTopPoint(1, 1, dieWidth, dieHeight).Y);
                    //dies.Add(tempDie);
                    JsonHelper.Serialize(dies, @"D:\QTWaferProgram\fuckingnew\fucking.json");
                    #endregion
                    break;

                case "随机加一个芯片":
                    double pixelLenght = 1.40624;
                    Point waferCenterP = new Point(139524, 114250);
                    double waferRadio = 99575;
                    //nonstandardWafermap1.WaferMinX = waferCenterP.X - waferRadio;
                    //nonstandardWafermap1.WaferMaxX = waferCenterP.X + waferRadio;
                    //nonstandardWafermap1.WaferMinY = waferCenterP.Y - waferRadio;
                    //nonstandardWafermap1.WaferMaxY = waferCenterP.Y + waferRadio;
                    //nonstandardWafermap1.AddDiesByRect(waferCenterP, new Point(84519, 92403), new Point(157365, 50000), waferRadio,  3000, 1000, 10, 16);
                    break;
            }
        }


        #region functions

        /// <summary>
        /// 图谱对位
        /// </summary>
        private void MappingContraposition()
        {
            if (wafermapLeft.Notchlocation != wafermapRight.Notchlocation) { DarkMessageBox.ShowError("对位失败，请先确认左右图谱一致"); return; }

            if (programConfig.IsNonstandardMapping)
            {
                if (nonWafermapLeft.Dataset == null || wafermapRight.Dataset == null) { DarkMessageBox.ShowError("请先加载图谱数据"); return; }
                nonWafermapLeft.Dataset = WaferMappingHelper.MappingContraposition(wafermapRight.Dataset, nonWafermapLeft.Dataset, productMappingArgs.OffsetXNum - 1, productMappingArgs.OffsetYNum - 1);
            }
            else
            {
                if (wafermapLeft.Dataset == null || wafermapRight.Dataset == null) { DarkMessageBox.ShowError("请先加载图谱数据"); return; }
                var finalData = WaferMappingHelper.MappingContraposition(wafermapRight.Dataset, wafermapLeft.Dataset, productMappingArgs.OffsetXNum - 1, productMappingArgs.OffsetYNum - 1);
                if (finalData == null) { DarkMessageBox.ShowError("对位失败，请先确认左右图谱一致"); return; }
                wafermapLeft.Dataset = finalData;
            }
        }


        /// <summary>
        /// 导出过滤的图谱
        /// </summary>
        private void ExportFilterMapping()
        {
            if (programConfig.IsNonstandardMapping && nonWafermapLeft.Dataset == null)
            {
                DarkMessageBox.ShowWarning("程式图谱为空，请先导入");
                return;
            }
            if(!programConfig.IsNonstandardMapping && wafermapLeft.Dataset == null)
            {
                DarkMessageBox.ShowWarning("程式图谱为空，请先导入");
                return;
            }
            if (programConfig.IsNonstandardMapping)
                JsonHelper.Serialize(nonWafermapLeft.Dataset, programConfig.GetMappingFileName() + ".filter");
            else
                JsonHelper.Serialize(wafermapLeft.Dataset, programConfig.GetMappingFileName() + ".filter");
            JsonHelper.Serialize(productMappingArgs, programConfig.GetMappingFilterArgs());
            DarkMessageBox.ShowInformation("已成功导出对位后的图谱，检测完成后会自动恢复默认的程式图谱", "恭喜");
            this.Close();
        }
        private void LoadSoftwareMapping() {
            string filePath2;
            OpenFileDialog fileDialog2 = new OpenFileDialog();
            fileDialog2.Title = "请选择图谱文件";
            fileDialog2.Filter = "图谱文件|*.txt|所有文件|*.*";
            fileDialog2.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog2.ShowDialog() == DialogResult.OK)
            {
                   //this.Text = string.Format("标准图谱-[{0}]", fileDialog2.FileName);
                filePath2 = Path.GetFullPath(fileDialog2.FileName);
                dlbPeoductMapinggFileName.Tag = fileDialog2.FileName;
                dlbPeoductMapinggFileName.Text = "已加载产品图谱: " + Path.GetFileName(fileDialog2.FileName);

                string[,] softwareMapping;
                if (programConfig.IsNonstandardMapping)
                {
                     softwareMapping = WaferMappingHelper.MappingAnalysis(filePath2, productMappingArgs);
                    nonWafermapRight.SetWaferInfo(programConfig.WaferCenter, programConfig.WaferRadius);
                    ////waferMap.SelectMultiple = false;
                    ////waferMap.OnDieClick += WaferMap_OnDieClick;
                    //nonWafermapRight.Colors = Die.DefaultColors;
                    ////var data = JsonHelper.DeserializeByFile<List<Die>>(@"D:\QTWaferProgram\test\result_mapping.txt");
                    ////nonWafermapRight.Dataset = JsonHelper.DeserializeByFile<List<Die>>(mappingFile);
                    //nonWafermapRight.Notchlocation = 90;
                    //nonWafermapRight.Visible = true;
                    //wafermapRight.Visible = false;

                }
                else
                {
                    softwareMapping = WaferMappingHelper.MappingAnalysis(filePath2, productMappingArgs);
                }
                if (softwareMapping == null) { DarkMessageBox.ShowError("加载的产品图谱有误，请重新选择"); return; }
                Die[,] data = WaferMappingHelper.GetDiesData(productMappingArgs, softwareMapping);

                //var data = JsonHelper.DeserializeByFile<Die[,]>(filePath2);
                wafermapRight.Dataset = data;
                wafermapRight.Notchlocation = 0;
                //wmap.MinimumSize = new Size(500, 500);
                wafermapRight.Interactive = false;
                wafermapRight.Visible = true;
                nonWafermapRight.Visible = false;
            }
            else
            {
                fileDialog2.Dispose();
            }
        }

        private void LoadMapping()
        {
            SelectProgram aa = new SelectProgram();
            aa.ShowDialog();
            if (aa.DialogResult == DialogResult.OK)
            {
                programConfig = aa.Tag as TestProgramConfig;
                if (programConfig == null)
                {
                    DarkMessageBox.ShowWarning("程式相关的配置文件丢失");
                    return;
                }

                //programConfig = JsonHelper.DeserializeByFile<TestProgramConfig>(Path.Combine(dir, "config.zyn"));
                dlbSoftwareMappingFileName.Tag = programConfig.Name;
                dlbSoftwareMappingFileName.Text = "已加载程式图谱: " + programConfig.Name; //Path.GetFileName(Path.GetDirectoryName(mappingFile.FileName));
                productMappingArgs = null;
                productMappingArgs = JsonHelper.DeserializeByFile<ProductMappingArgs>(programConfig.GetMappingFilterArgs());
                if (productMappingArgs == null) productMappingArgs = ProductMappingArgs.Default();
                propertyGrid1.SelectedObject = productMappingArgs;
                if (programConfig.IsNonstandardMapping)
                {

                    nonWafermapLeft.SetWaferInfo(programConfig.WaferCenter, programConfig.WaferRadius);
                    //waferMap.SelectMultiple = false;
                    //waferMap.OnDieClick += WaferMap_OnDieClick;
                    nonWafermapLeft.Colors = Die.DefaultColors;

                    //var data = JsonHelper.DeserializeByFile<List<Die>>(@"D:\QTWaferProgram\test\result_mapping.txt");
                    nonWafermapLeft.Dataset = JsonHelper.DeserializeByFile<List<Die>>(programConfig.GetMappingFileName());
                    nonWafermapLeft.Notchlocation = 90;
                    nonWafermapLeft.Visible = true;
                    wafermapLeft.Visible = false;

                }
                else
                {
                    wafermapLeft.Dataset = JsonHelper.DeserializeByFile<Die[,]>(programConfig.GetMappingFileName());
                    nonWafermapLeft.Visible = false;
                    wafermapLeft.Visible = true;
                }

            }
        }
            
        /// <summary>
        /// 旋转
        /// </summary>
        /// <param name="angle"></param>
        private void RotateProductMapping(int angle = 90)
        {
            var orignalDies = wafermapRight.Dataset;
            wafermapRight.Dataset = WaferMappingHelper.RotateMapping(orignalDies, angle);
            wafermapRight.Notchlocation += angle;
            switch (wafermapRight.Notchlocation)
            {
                case 0:
                case 360:
                    productMappingArgs.WaferNotchLocation = ProductMappingArgs.NotchLocation.下;
                    break;
                case 90:
                    productMappingArgs.WaferNotchLocation = ProductMappingArgs.NotchLocation.左;
                    break;
                case 180:
                    productMappingArgs.WaferNotchLocation = ProductMappingArgs.NotchLocation.上;
                    break;
                case 270:
                    productMappingArgs.WaferNotchLocation = ProductMappingArgs.NotchLocation.右;
                    break;
            }
            propertyGrid1.SelectedObject = productMappingArgs;
        }
        #endregion

        private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            //if (NotRefresh) return;
            string fileName = "";
            if (dlbPeoductMapinggFileName.Tag != null) fileName = dlbPeoductMapinggFileName.Tag.ToString();
            else return;

            if (productMappingArgs.FilterDieCharStartIndex > productMappingArgs.DieCharLenght - 1)
            {
                DarkMessageBox.ShowError("OK芯片标识在单个芯片字符串中的起始位置不能大于单个芯片的字符长度，请重新输入");
                return;
            }
            if (productMappingArgs.FilterDieCharStartIndex + productMappingArgs.FilterDieCharLength > productMappingArgs.DieCharLenght)
            {
                DarkMessageBox.ShowError("OK芯片标识在单个芯片字符串中的结束位置超出单个芯片字符串长度，请重新输入");
                return;
            }
            //Console.WriteLine(JsonHelper.Serialize(productMappingArgs));
            //return;

            var softwareMapping = WaferMappingHelper.MappingAnalysis(fileName, productMappingArgs);
            if (softwareMapping == null) { DarkMessageBox.ShowError("加载的产品图谱有误，请重新选择"); return; }
            Die[,] data = WaferMappingHelper.GetDiesData(productMappingArgs, softwareMapping);

            productMappingArgs.WaferNotchLocation = ProductMappingArgs.NotchLocation.下;
            propertyGrid1.SelectedObject = productMappingArgs;
            //var data = JsonHelper.DeserializeByFile<Die[,]>(filePath2);
            wafermapRight.Dataset = data;
            wafermapRight.Notchlocation = 0;
            //wmap.MinimumSize = new Size(500, 500);
            //wafermap2.Interactive = true;
        }

        private void ProductToolStripMenuItem_Save_Click(object sender, EventArgs e)
        {
            string filePath2;
            SaveFileDialog fileDialog2 = new SaveFileDialog();
            fileDialog2.Title = "请选择图谱文件";
            fileDialog2.Filter = "图谱文件|*.zyn";
            fileDialog2.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog2.ShowDialog() == DialogResult.OK)
            {
                JsonHelper.Serialize(wafermapRight.Dataset, Path.GetFullPath(fileDialog2.FileName));
            }
            else
            {
                fileDialog2.Dispose();
            }
        }
    }
}
